// Simple API client with JWT handling and error normalization
const ApiClient = (() => {
  const STORAGE_TOKEN_KEY = 'rr_token';
  const STORAGE_USER_KEY = 'rr_user';

  function getToken() {
    try {
      return localStorage.getItem(STORAGE_TOKEN_KEY);
    } catch (_) {
      return null;
    }
  }

  function setToken(token) {
    try {
      localStorage.setItem(STORAGE_TOKEN_KEY, token || '');
    } catch (_) {}
  }

  function setUser(user) {
    try {
      localStorage.setItem(STORAGE_USER_KEY, JSON.stringify(user || null));
    } catch (_) {}
  }

  function getUser() {
    try {
      const raw = localStorage.getItem(STORAGE_USER_KEY);
      return raw ? JSON.parse(raw) : null;
    } catch (_) {
      return null;
    }
  }

  function clearAuth() {
    setToken('');
    setUser(null);
  }

  async function request(path, { method = 'GET', headers = {}, body } = {}) {
    const token = getToken();
    const finalHeaders = { 'Content-Type': 'application/json', ...headers };
    if (token) finalHeaders['Authorization'] = `Bearer ${token}`;

    const res = await fetch(path, {
      method,
      headers: finalHeaders,
      body: body ? JSON.stringify(body) : undefined,
      credentials: 'same-origin'
    });

    let data;
    const contentType = res.headers.get('content-type') || '';
    if (contentType.includes('application/json')) {
      data = await res.json();
    } else {
      const text = await res.text();
      data = { code: res.status, message: text, data: null };
    }

    // 鉴权失败统一处理：HTTP 401 或 业务码 401/1006/2017/2018
    if (res.status === 401 || data.code === 401 || data.code === 1006 || data.code === 2017 || data.code === 2018) {
      clearAuth();
      if (!location.pathname.endsWith('/login.html')) {
        location.href = '/login.html';
      }
      throw new Error('UNAUTHORIZED');
    }

    if (!res.ok || (data && data.code && data.code !== 200)) {
      const msg = (data && (data.message || data.msg)) || res.statusText || '请求失败';
      throw new Error(msg);
    }

    return data && data.data !== undefined ? data.data : data;
  }

  return {
    getToken,
    setToken,
    setUser,
    getUser,
    clearAuth,
    get: (path) => request(path, { method: 'GET' }),
    post: (path, body) => request(path, { method: 'POST', body }),
    put: (path, body) => request(path, { method: 'PUT', body }),
    delete: (path) => request(path, { method: 'DELETE' })
  };
})();

// Domain-specific APIs
const UsersApi = {
  login: (principal, password) => ApiClient.post('/api/users/login', { principal, password }),
  register: (payload) => ApiClient.post('/api/users/register', payload),
  me: () => ApiClient.get('/api/users/me'),
  updateMe: (payload) => ApiClient.put('/api/users/me', payload),
  favorites: (page = 1, size = 20) => ApiClient.get(`/api/users/favorites?page=${page}&size=${size}`),
  addFavorite: (characterId) => ApiClient.post(`/api/users/favorites?characterId=${characterId}`),
  removeFavorite: (characterId) => ApiClient.delete(`/api/users/favorites/${characterId}`)
};

const CharactersApi = {
  list: (params = {}) => {
    const q = new URLSearchParams(params).toString();
    return ApiClient.get(`/api/characters${q ? `?${q}` : ''}`);
  },
  get: (id) => ApiClient.get(`/api/characters/${id}`),
  search: (q, params = {}) => {
    const query = new URLSearchParams({ q, ...params }).toString();
    return ApiClient.get(`/api/characters/search?${query}`);
  },
  trending: () => ApiClient.get('/api/recommendations/characters:trending'),
  recommendations: () => {
    const user = ApiClient.getUser();
    const suffix = user && user.id ? `?userId=${encodeURIComponent(user.id)}` : '';
    return ApiClient.get(`/api/recommendations/characters${suffix}`);
  }
};

const ConversationsApi = {
  create: ({ characterId, title, skillType }) => ApiClient.post('/api/conversations', { characterId, title, skillType }),
  list: (page = 1, size = 20, characterId = null) => {
    const params = new URLSearchParams({ page, size });
    if (characterId) params.append('characterId', characterId);
    return ApiClient.get(`/api/conversations?${params.toString()}`);
  },
  messages: (conversationId, page = 1, size = 50) => ApiClient.get(`/api/conversations/${conversationId}/messages?page=${page}&size=${size}`),
  sendMessage: (conversationId, content) => ApiClient.post(`/api/conversations/${conversationId}/messages`, { content }),
  delete: (conversationId) => ApiClient.delete(`/api/conversations/${conversationId}`),
  cleanEmpty: () => ApiClient.delete('/api/conversations/clean-empty'),
  
  // 流式发送消息
  streamMessage: (conversationId, content, onChunk, onComplete, onError) => {
    const token = ApiClient.getToken();
    if (!token) {
      onError(new Error('未登录'));
      return null;
    }

    // 直接使用fetch进行流式请求
    fetch(`/api/streaming/conversations/${conversationId}/messages`, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json',
        'Accept': 'text/event-stream'
      },
      body: JSON.stringify({ content })
    }).then(response => {
      console.log('SSE响应状态:', response.status);
      if (!response.ok) {
        console.error('SSE响应错误:', response.status, response.statusText);
        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
      }
      
      const reader = response.body.getReader();
      const decoder = new TextDecoder();
      let buffer = ''; // 添加缓冲区来处理分块数据
      
      function readStream() {
        reader.read().then(({ done, value }) => {
          if (done) {
            onComplete();
            return;
          }
          
          const chunk = decoder.decode(value, { stream: true });
          console.log('收到SSE数据块:', chunk);
          
          // 将新数据添加到缓冲区
          buffer += chunk;
          
          // 按行分割缓冲区
          const lines = buffer.split('\n');
          
          // 保留最后一行（可能不完整）
          buffer = lines.pop() || '';
          
          for (const line of lines) {
            console.log('处理SSE行:', line);
            if (line.startsWith('data: ')) {
              const data = line.substring(6);
              console.log('提取数据:', data);
              if (data === '[DONE]') {
                console.log('收到完成信号');
                onComplete();
                return;
              }
              if (data && data !== '') {
                console.log('调用onChunk:', data);
                onChunk(data);
              }
            }
          }
          
          readStream();
        }).catch(error => {
          onError(error);
        });
      }
      
      readStream();
      
    }).catch(error => {
      console.error('SSE请求失败:', error);
      onError(error);
    });

    // 返回一个简单的对象，表示流式请求已启动
    return { close: () => {} };
  }
};

const PreferencesApi = {
  get: () => ApiClient.get('/api/users/preferences'),
  update: (payload) => ApiClient.put('/api/users/preferences', payload)
};


